<style lang="less">
@import "department.less";
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="add" type="primary" icon="md-add">添加子部门</Button>
        <Button @click="delAll" icon="md-trash">批量删除</Button>
        <Button @click="getParentList" icon="md-refresh">刷新</Button>
      </Row>
      <Row type="flex" justify="start" class="code-row-bg">
        <i-col span="6">
          <Alert show-icon>
            当前选择编辑： <span class="select-count">{{editTitle}}</span>
            <a class="select-clear" v-if="form.id" @click="cancelEdit">取消选择</a>
          </Alert>
          <Input v-model="searchKey" suffix="ios-search" @on-change="search" placeholder="请输入部门名搜索" />
          <div class="tree-bar">
            <Tree ref="tree" :data="data" :load-data="loadData" show-checkbox @on-check-change="changeSelect"
              @on-select-change="selectTree"></Tree>
          </div>
          <Spin size="large" fix v-if="loading"></Spin>
        </i-col>
        <i-col span="14">
          <Form ref="form" :model="form" :label-width="80" :rules="menuFormValidate" :disabled="isDisable">
            <FormItem label="上级部门" prop="parentTitle">
              <Input v-model="form.parentTitle" disabled />
            </FormItem>
            <FormItem label="部门名称" prop="title">
              <Input v-model="form.title" />
            </FormItem>
            <FormItem label="排序值" prop="sortOrder">
              <InputNumber :max="1000" :min="0" v-model="form.sortOrder"></InputNumber>
              <span style="margin-left:5px">值越小越靠前，支持小数</span>
            </FormItem>
            <FormItem label="是否启用" prop="status">
              <Select v-model="form.status" placeholder="请选择" clearable>
                <Option value="1">正常</Option>
                <Option value="0">禁用</Option>
              </Select>
            </FormItem>
            <div style="max-height: 2000px;margin-left: 40px;">
              <Row>
                <i-col span="11">
                  <fieldset>
                    <legend><strong>新车展业区域</strong></legend>
                    <div class="auto"> 
                    <Tree ref="editNewCarTree" :data="editNewCarRegionData" show-checkbox
                      @on-check-change="newCarChangeSelect"></Tree>
                    </div>
                  </fieldset>
                </i-col>
                <i-col span="11" class="col-legend">
                  <fieldset >
                    <legend><strong>二手车展业区域</strong></legend>
                    <div class="auto"> 
                    <Tree ref="editOldCarTree" :data="editOldCarRegionData" show-checkbox
                      @on-check-change="oldCarChangeSelect"></Tree>
                    </div>
                  </fieldset>
                </i-col>
              </Row>
            </div>
            <Form-item style="margin-top:10px;text-align: center;">
              <Button @click="submitEdit" :loading="submitLoading" type="primary" icon="ios-create-outline">修改并保存
              </Button>
              <Button @click="handleReset" style="margin-left: 10px;">重置</Button>
              <Button @click="delbyId" style="margin-left: 10px;" type="error" icon="md-trash">删除</Button>
            </Form-item>
          </Form>
        </i-col>
      </Row>
    </Card>

    <Modal class="modal-class" :title="modalTitle" v-model="menuModalVisible" :mask-closable='false' :width="800">
      <Form ref="formAdd" :model="formAdd" :label-width="85" :rules="menuFormValidate">
        <div v-if="showParent">
          <FormItem label="上级部门：">
            <Input v-model="form.title" disabled />
          </FormItem>
        </div>
        <FormItem label="部门名称" prop="title">
          <Input v-model="formAdd.title" />
        </FormItem>
        <FormItem label="排序值" prop="sortOrder">
          <InputNumber :max="1000" :min="0" v-model="formAdd.sortOrder"></InputNumber>
          <span style="margin-left:5px">值越小越靠前，支持小数</span>
        </FormItem>
        <FormItem label="是否启用" prop="status">
          <Select v-model="formAdd.status" placeholder="请选择" clearable>
            <Option value="1">正常</Option>
            <Option value="0">禁用</Option>
          </Select>
        </FormItem>
        <div style="height: 350px;overflow:auto ">
          <Row>
            <i-col span="11">
              <fieldset>
                <legend><strong>新车展业区域</strong></legend>
                <Tree ref="newCarTree" :data="newCarRegionData" :load-data="loadNewCarRegionData" show-checkbox
                  @on-check-change="newCarChangeSelect"></Tree>
              </fieldset>
            </i-col>
            <i-col span="11" class="col-legend">
              <fieldset>
                <legend><strong>二手车展业区域</strong></legend>
                <Tree ref="oldCarTree" :data="oldCarRegionData" :load-data="loadOldCarRegionData" show-checkbox
                  @on-check-change="oldCarChangeSelect"></Tree>
              </fieldset>
            </i-col>
          </Row>
        </div>

      </Form>
      <div slot="footer">
        <Button type="text" @click="cancelAdd">取消</Button>
        <Button type="primary" :loading="submitLoading" @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  initOldCarRegion,
  initNewCarRegion,
  initDepartment,
  addDepartment,
  editDepartment,
  deleteDepartment,
  searchDepartment,
  channelSearch,
  delByIdDepartment
} from "_p/afs-apply/api/apply-admin/department/department";
import { user } from "@/store/modules/user";
import { deepClone } from "@/libs/utils/ObjectClone";

export default {
  data() {
    return {
      isDisable: "",
      defParentCode: "0",
      loading: true,
      menuModalVisible: false,
      selectList: [],
      newCarSelectList: [],
      oldCarSelectList: [],
      selectCount: 0,
      showParent: false,
      modalTitle: "",
      editTitle: "",
      searchKey: "",
      form: {
        id: "",
        parentId: "",
        parentTitle: "",
        sortOrder: null,
        status: 0,
        newCarRegion: [],
        oldCarRegion: []
      },
      formAdd: {},
      menuFormValidate: {
        title: [{ required: true, message: "名称不能为空", trigger: "blur" }]
      },
      submitLoading: false,
      data: [],
      oldCarRegionData: [],
      newCarRegionData: [],
      editNewCarRegionData: [],
      editOldCarRegionData: []
    };
  },
  methods: {
    init() {
      this.getParentList();
    },
    getParentList() {
      this.loading = true;
      initDepartment(this.defParentCode).then(res => {
        this.loading = false;
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          this.data = res.data;
        }
      });
    },
    loadData(item, callback) {
      console.log("这个是点开下一级触发的事件");
      initDepartment(item.id).then(res => {
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
            if (e.status === "0") {
              e.title = "[已禁用]" + e.title;
            }
          });
          callback(res.data);
        }
      });
    },
    loadOldCarRegionData(item, callback) {
      initOldCarRegion(item.channelId, item.code, item.deptId).then(res => {
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.data);
        }
      });
    },
    loadNewCarRegionData(item, callback) {
      initNewCarRegion(item.channelId, item.code, item.deptId).then(res => {
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          callback(res.data);
        }
      });
    },
    search() {
      if (this.searchKey) {
        this.loading = true;
        channelSearch(this.searchKey).then(res => {
          this.loading = false;
          if (res.code === "0000") {
            this.data = res.data;
          }
        });
      } else {
        this.getParentList();
      }
    },
    selectTree(v) {
      console.log("这个是选择后触发的事件");
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] === null) {
            v[0][attr] = "";
          }
        }
        let str = JSON.stringify(v[0]);
        let data = JSON.parse(str);
        this.form = data;
        console.log(this.form)
        console.log(data.parentId);
        if (data.parentId == "0") {
          this.isDisable = true;
        } else {
          this.isDisable = false;
        }
        console.log(data.title)
        this.form.title=this.form.title.replace("[已禁用]","")
        console.log(this.form.title.replace("[已禁用]",""))
        console.log(data.title.replace("[已禁用]",""))
        this.editTitle = data.title.replace("[已禁用]","");
        this.editNewCarRegionData = data.newCarRegion;
        this.editOldCarRegionData = data.oldCarRegion;
      } else {
        this.cancelEdit();
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0];
      if (data) {
        data.selected = false;
      }
      this.$refs.form.resetFields();
      delete this.form.id;
      this.editTitle = "";
      this.editOldCarRegionData = [];
      this.editNewCarRegionData = [];
    },
    cancelAdd() {
      this.newCarRegionData = [];
      this.oldCarRegionData = [];
      this.menuModalVisible = false;
    },
    submitEdit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.id) {
            this.$Message.warning("请先点击选择要修改的部门");
            return;
          }
          this.submitLoading = true;
          if (this.form.sortOrder === null) {
            this.form.sortOrder = "";
          }
          this.form.newCarRegion = this.$refs.editNewCarTree.getCheckedAndIndeterminateNodes();
          this.form.oldCarRegion = this.$refs.editOldCarTree.getCheckedAndIndeterminateNodes();
          console.log(this.form.newCarRegion);
          console.log(this.form.oldCarRegion);
          editDepartment(this.form)
            .then(res => {
              this.submitLoading = false;
              if (res.code === "0000") {
                this.$Message.success(res.msg);
                this.init();
              }
            })
            .catch(error => {
              console.error(error);
              this.submitLoading = false;
            });
        }
      });
    },
    handleReset() {
      this.$refs.form.resetFields();
      this.editStatus = true;
      this.form.status = 0;
      this.editOldCarRegionData = [];
      this.editNewCarRegionData = [];
    },
    submitAdd() {
      this.$refs.formAdd.validate(valid => {
        if (valid) {
          if (this.formAdd.sortOrder === null) {
            this.formAdd.sortOrder = "";
          }
          if (
            this.formAdd.status == "" ||
            this.formAdd.status == null ||
            this.formAdd.status == undefined
          ) {
            this.formAdd.status = "1";
          }
          this.formAdd.newCarRegion = this.$refs.newCarTree.getCheckedAndIndeterminateNodes();
          this.formAdd.oldCarRegion = this.$refs.oldCarTree.getCheckedAndIndeterminateNodes();
          if(this.formAdd.newCarRegion.length==0&&this.formAdd.oldCarRegion.length==0){
               this.$Message.warning("请选择授权区域！");
                return;
          }
          this.submitLoading = true;
          addDepartment(this.formAdd)
            .then(res => {
              this.submitLoading = false;
              if (res.code === "0000") {
                this.$Message.success(res.msg);
                this.init();
                this.menuModalVisible = false;
                this.newCarRegionData = [];
                this.oldCarRegionData = [];
              }
            })
            .catch(error => {
              console.error(error);
              this.submitLoading = false;
            });
        }
      });
    },

    add() {
      if (this.form.id == "" || this.form.id == null) {
        this.$Message.warning("请先点击选择一个部门");
        return;
      }
      this.modalTitle = "添加子部门";
      this.showParent = true;
      this.formAdd = {
        parentId: this.form.id,
        sortOrder: 1,
        status: 0
      };
      initNewCarRegion(
        this.form.channelId,
        this.defParentCode,
        this.form.id
      ).then(res => {
        console.log(this.form.channelId, this.defParentCode, this.form.id);
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          this.newCarRegionData = deepClone(res.data);
        }
      });
      initOldCarRegion(
        this.form.channelId,
        this.defParentCode,
        this.form.id
      ).then(res => {
        if (res.code === "0000") {
          res.data.forEach(function(e) {
            if (e.isParent) {
              e.loading = false;
              e.children = [];
            }
          });
          this.oldCarRegionData = deepClone(res.data);
        }
      });
      this.menuModalVisible = true;
    },
    newCarChangeSelect(v) {
      this.newCarSelectList = v;
    },
    oldCarChangeSelect(v) {
      this.oldCarSelectList = v;
    },
    changeSelect(v) {
      console.log("这是触发的什么事件");
      this.selectCount = v.length;
      this.selectList = v;
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning("您还未勾选要删除的数据");
        return;
      }
      this.$Modal.confirm({
        title: "确认删除",
        content: "您确认要删除所选的 " + this.selectCount + " 条数据?",
        onOk: () => {
          let ids = "";
          this.selectList.forEach(function(e) {
            ids += e.id + ",";
          });
          ids = ids.substring(0, ids.length - 1);
          deleteDepartment(ids).then(res => {
            if (res.code === "0000") {
              this.$Message.success("删除成功");
              this.selectList = [];
              this.selectCount = 0;
              this.cancelEdit();
              this.init();
            }
          });
        }
      });
    },
    delbyId() {
      if (!this.form.id) {
        this.$Message.warning("请先点击选择要修改的部门");
        return false;
      }
      delByIdDepartment(this.form.id).then(res => {
        if (res.code === "0000") {
          this.$Message.success("删除成功");
          this.selectList = [];
          this.selectCount = 0;
          this.cancelEdit();
          this.init();
        }
      });
    }
  },

  mounted() {
    this.init();
  }
};
</script>
